const KEY = CryptoJS.enc.Utf8.parse("J2f9UcMe55plh4gV");
  const KEY2 = CryptoJS.enc.Utf8.parse("njjcxxkj02504596");
  const IV = CryptoJS.enc.Utf8.parse('02504596njjcxxkj');
  /**
   * AES加密 ：字符串 key iv  返回base64
   */
  let apiListDataOld = {
      gy: [],
      sy: []
  }
  let apiListData = []
  
  function getApiData(proId) {
      let url = baseUrl + "/tApiFunction/getTreeListByProId";
      setTimeout(() => {
          $.ajax({
              type: "post",
              dataType: "json",
              contentType: "application/json",
              url: url,
              data: JSON.stringify({
                  iscommon: 1
              }),
              success: function(res) {
                  apiListDataOld.gy = res.data
                  for (let i = 0; i < res.data.length; i++) {
                      res.data[i].child.map(data => {
                          let pars = {}
                          data.inputParams = data.inputParams || []
                          data.inputParams.map(v => {
                              pars[v.paramKey] = {
                                  dataType: v.dataType
                              }
                          })
                          apiListData[data.funName] = {
                              type: data.type,
                              par: pars
                          }
                      })
                  }
                  getApiDataSY(proId)
              }
          })
      }, 500)
  }
  
  function getApiDataSY(proId) {
      let url = baseUrl + "/tApiFunction/getTreeListByProId";
      setTimeout(() => {
          $.ajax({
              type: "post",
              dataType: "json",
              contentType: "application/json",
              url: url, //路径
              data: JSON.stringify({
                  iscommon: 0,
                  proId: proId
              }),
              success: function(res) {
                  apiListDataOld.sy = res.data.filter(v => {
                      return proId == v.proId
                  })
                  for (let i = 0; i < res.data.length; i++) {
                      let pars = {}
                      let data = res.data[i]
                      data.inputParams = data.inputParams || []
                      data.inputParams.map(v => {
                          pars[v.paramKey] = {
                              dataType: v.dataType
                          }
                      })
                      apiListData[data.funName] = {
                          type: data.type,
                          par: pars
                      }
                  }
                  sdkData.apiTreeList = apiListData
                  apiTreeList = {}
              }
          })
      }, 500)
  }
  /**
   * AES加密 ：字符串 key iv  返回base64
   */
  function encryptECB(word, EK) {
      if (word === null) {
          return word;
      }
      let srcs = CryptoJS.enc.Utf8.parse(word);
      let encrypted = CryptoJS.AES.encrypt(srcs, KEY, {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.Pkcs7
      });
      return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
  }
  
  function Encrypt(word, keyStr, ivStr) {
      let key = KEY2;
      let iv = IV;
      if (keyStr) {
          key = CryptoJS.enc.Utf8.parse(keyStr);
          iv = CryptoJS.enc.Utf8.parse(ivStr);
      }
      let srcs = CryptoJS.enc.Utf8.parse(word);
      var encrypted = CryptoJS.AES.encrypt(srcs, key, {
          iv: iv,
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.ZeroPadding
      });
      return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
  }
  /**
   1. AES 解密 ：字符串 key iv  返回base64
   2.  3. @return {string}
   */
  
  let bEncrypt = true;
  
  function decryptECB(word, EK) {
      if (word === null) {
          return word;
      }
      let key = KEY;
      let encryptedHexStr = CryptoJS.enc.Base64.parse(word);
      let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
      let decrypt = CryptoJS.AES.decrypt(srcs, key, {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.Pkcs7
      });
      let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
      return decryptedStr.toString();
  }
  let UEdataList = {},
      apiTreeList = {},
      successType = false,
      isCheckout = false,
      functionId = "",
      apiName = "jinBoxAPI";
  let ue = {
      interface: {}
  }
  $(() => {
      try {
          UEdataList = sdkData.UEdataList;
          apiTreeList = sdkData.apiTreeList;
          isCheckout = sdkData.isCheckout;
          successType = true;
      } catch (e) {
          successType = false;
      };
      if (!successType) {
          let mySdkMsg = new sdkMsg();
          mySdkMsg.error("sdkData.js未加载,错误号:errorCode=> 000001");
          return;
      };
  })
  jinBoxAPI = function(t, e, f, tr) {
          if (JSON.stringify(apiTreeList) == '{}') {
              try {
                  UEdataList = sdkData.UEdataList;
                  apiTreeList = sdkData.apiTreeList;
                  isCheckout = sdkData.isCheckout;
                  successType = true;
              } catch (e) {
                  successType = false;
              };
              if (!successType) {
                  let mySdkMsg = new sdkMsg();
                  mySdkMsg.error("sdkData.js未加载,错误号:errorCode=> 000001");
                  return;
              };
          }
          if (!e.noProof) {
              if (!apiTreeList[t]) {
                  let mySdkMsg = new sdkMsg();
                  mySdkMsg.error("无法调用当前接口(接口名: " + t + ")！请联系管理员,错误号:errorCode=> 100001");
                  return;
              };
          }
          if (!e.noProofPar) {
              if (!checkout(t, e)) {
                  return;
              };
          }
          e = e ? e : {};
          let isBack = false;
          let functionId = ''
          if (f) {
              isBack = true;
              functionId = new Date().getTime() + "";
              UEback[functionId] = f;
              ue.interface[functionId] = f
          };
          let ws = "";
          msgSend(ws, t, e, isBack, functionId);
      }
      /*mqtt 创建连接
        clientId: "133_web_1676471521230"
        clientName: "133_web_1676471521230"
        password: ""
        topic: "hznz_topic"
        userName: ""
        wsUrl: "ws:192.168.2.63:8083/mqtt"
      */
  let clientObj = {
      client: "",
      id: "",
      topic: "",
      userName: "",
  }
  let UEback = {}
  initMQTT = function(obj) {
          bEncrypt = obj.bEncrypt || false
          const mqttConfig = {
              /* 客户端ID（注意：客户端不能写死，如果多人用同一个客户端，那么就会出现MQTT一直是断开重连断开重连的问题）*/
              clientId: obj.clientId,
              clean: true,
              reconnectPeriod: 5000,
              /* 1000毫秒，两次重新连接之间的间隔 */
              /* connectTimeout: 30 * 1000, // 1000毫秒，两次重新连接之间的间隔 */
              username: obj.userName,
              /* 账户名密码没就不用写 */
              password: obj.password
          };
          clientObj.userName = obj.userName;
          clientObj.id = obj.clientId;
          clientObj.topic = obj.topic;
          clientObj.client = mqtt.connect(obj.wsUrl, mqttConfig);
          clientObj.client.on("connect", (e) => {
              clientObj.client.subscribe(obj.topic, {
                  qos: 0
              }, function(e) {})
          });
          /*信息监听事件*/
          clientObj.client.on("message", mqttMessage);
      }
      /* mqtt关闭 */
  function closeLian() {
      clearTimeout(reconnectionTime)
      if (clientObj.client) {
          clientObj.client.unsubscribe(clientObj.topic, (error) => {
              if (error) {
                  console.log("Unsubscribe error:", error)
              }
          });
          clientObj.client.end();
          clientObj.client = null
          UEback = {}
      }
  }
  // mqtt接收消息方法
  function mqttMessage(topic, message, packet) {
      let backMsg = packet.payload.toString();
      if (bEncrypt) {
          backMsg = decryptECB(backMsg)
      }
      try {
          backMsg = JSON.parse(backMsg);
      } catch (error) {
          backMsg = backMsg;
      }
  
      let name = backMsg.functionId || backMsg.FunctionId
      if (UEback[name]) {
          UEback[name](backMsg);
      }else if (ue.interface[name]) {
          ue.interface[name](backMsg);
      }
      if (name == 'webCloseUser' && backMsg.userId == clientObj.id) {
          closeLian()
          $("#yxrIframe").attr("src", '');
          showPopByInfo('用户被管理员踢下线')
      }
      if (name == 'webRefreshUser') {
          showPopByInfo('重新获取流中...')
          closeLian()
          $("#yxrIframe").attr("src", '');
          setTimeout(() => {
              reconnection = true;
              initApiFun(initApiFunPar.proId, initApiFunPar.sid, initApiFunPar.callBack, initApiFunPar.type, initApiFunPar.bEncrypt, initApiFunPar.inType)
          }, 5000);
      }
      if (name == 'webCloseUserBySelf' && backMsg.userId == clientObj.id) {
          closeLian()
          $("#yxrIframe").attr("src", '');
          showPopByInfo('用户在其它地方登录')
      }
  
  }
  let reconnection = false;
  let reconnectionTime = '';
  
  function msgSend(ws, BranchFun, BranchOption, isBack, functionId) {
      let type = apiTreeList[BranchFun] ? apiTreeList[BranchFun].type : "SpecialEvent";
      delete BranchOption.noProof
      delete BranchOption.noProofPar
      let par = {}
      if (BranchOption.isAutoDebugger) {
          delete BranchOption.isAutoDebugger
          par = BranchOption.text
      } else {
          par = {
              "type": type,
              "msg": {
                  "Branch": type,
                  "Option": {
                      "Branch": BranchFun,
                      "Option": BranchOption
                  },
                  "CallBack": {
                      "bIsBack": isBack,
                      "FunctionId": functionId
                  }
              }
          }
      }
      let message = bEncrypt ? encryptECB(JSON.stringify(par)) : (typeof par == 'string') ? par : JSON.stringify(par)
      if (clientObj.client) {
          clientObj.client.publish(clientObj.topic, message);
      }
  }
  let initApiFunPar = {}
  
  function getQueryString(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var url = window.location.href.split('?');
      var result = url[1] ? url[1].match(reg) : null;
      if (result != null) return unescape(result[2]);
      return null;
  }
  
  function initApiFun(proId, sid, callBack, type, isbEncrypt,inType) {
      closeLian()
      clearTimeout(reconnectionTime)
      proId = parProId == 'apiParProId' ? proId : parProId
      sid = parSid == 'apiParSid' ? sid : parSid
      type = parType == 'apiParType' ? type : parType
      isbEncrypt = parIsbEncrypt == 'apiParIsbEncrypt' ? isbEncrypt : parIsbEncrypt
      baseUrl = parBaseUrl && parBaseUrl == 'apiParBaseUrl' ? baseUrl : parBaseUrl
      type = type ? type : "web";
      bEncrypt = (isbEncrypt == 'true' || isbEncrypt == true)
      inType = inType?inType:''
      initApiFunPar = {
          proId,
          sid,
          callBack,
          type,
          bEncrypt,
          inType,
      }
      getIsAuthentication(proId, sid, callBack, type, bEncrypt)
  }
  
  function getIsAuthentication(proId, sid, callBack, type, bEncrypt) {
      $.ajax({
          type: "get",
          dataType: "json",
          contentType: "application/json",
          url: baseUrl + "/ue/getInstanceByInspect?projectId=" + proId + (type == 'web' ? "&serverId=" : "&instanceId=") + sid +
              "&type=" + (type == 'webDevelop'?'web':type) + '&bEncrypt=false',
          success: function(res) {
              if (res.status == 1) {
                  if (res.data.inspect == 0) {
                      let key = localStorage.getItem('edouardSDKTokenApi') || ''
                      nextInit(proId, sid, callBack, type, bEncrypt, key)
                  } else {
                      getSecQXFun()
                  }
              } else {
                  closeLian()
                  $("#yxrIframe").attr("src", '');
                  showPopByInfo(res.message)
                  reconnectionTime = setTimeout(()=>{
                    initApiFun(initApiFunPar.proId, initApiFunPar.sid, initApiFunPar.callBack, initApiFunPar.type, initApiFunPar.bEncrypt, initApiFunPar.inType)
                  },3000)
              }
          }
      })
  }
  
  function showPopByInfo(message) {
      let htmls = errInfoPop.replace('errorInfoTxt', message)
      if ($('.centerDiv').length > 0) {
          $('.centerDiv').append(htmls)
      } else {
          appendPop(htmls)
      }
  }
  function removePop(){
      $('.positionPop').remove()
  }
  function appendPop(htmls) {
      removePop()
      $("#yxrIframe").parent().append(htmls)
      $('.positionPop').css({
          left: $("#yxrIframe").offset().left,
          top: $("#yxrIframe").offset().top,
          width: $("#yxrIframe").innerWidth(),
          height: $("#yxrIframe").innerHeight()
      })
      let ws = $("#yxrIframe").innerWidth() / 1920
      let hs = $("#yxrIframe").innerHeight() / 930;
      let s = ws < hs ? ws : hs;
      $('.positionPop > div').css({
          transform: 'translate(-50%, -50%) scale(' + s + ')'
      })
  }
  
  function nextInit(proId, sid, callBack, type, isbEncrypt, key) {
      let url = baseUrl + "/ue/getConfigByPro?projectId=" + proId + (type == 'web' ? "&serverId=" : "&instanceId=") + sid +
          "&type=" + (type == 'webDevelop'?'web':type) + (isbEncrypt != 'undefined' ? ('&bEncrypt=' + isbEncrypt) : '')+(initApiFunPar.inType?'&inType='+initApiFunPar.inType:''),
          par = {};
      const mySdkMsg = new sdkMsg();
      if (!proId) {
          mySdkMsg.error("当前初始化API时,没有传入项目ID!,错误号:errorCode=> 200001");
          return;
      }
      $.ajax({
          type: "get",
          dataType: "json",
          contentType: "application/json",
          headers: {
              Token: key
          },
          url: url, //路径
          success: function(res) {
              if (isbEncrypt) {
                  res = decryptECB(res)
                  try {
                      res = JSON.parse(res);
                  } catch (error) {}
              }
              initAjaxEnd(res, callBack, key, isbEncrypt)
          },
          error: function(res) {
              let responseText = res.responseText
              if (isbEncrypt) {
                  responseText = JSON.parse(decryptECB(res.responseText))
              } else {
                  responseText = JSON.parse(responseText);
              }
              initAjaxEnd(responseText, callBack, key, isbEncrypt)
          }
      })
  }
  
  function initAjaxEnd(res, callBack, key, isbEncrypt) {
      console.log(res)
      if (res.status == 1) {
          removePop()
          if (res.data.inspect == 0) {
              if (callBack) {
                  callBack(res.data);
              };
              if ($("#yxrIframe").length != 1) {
                  mySdkMsg.info("当前页面未发现ID为yxrIframe的iframe元素！无法渲染云地址！,错误号:errorCode=> 900001");
              }
              if (res.data) {
                  res.data.bEncrypt = isbEncrypt
                  initMQTT(res.data);
                  if (res.data.frontUrl) {
                      $("#yxrIframe").attr("src", res.data.frontUrl + '?id=3dxr');
                  }
              }
              return;
          } else {
              console.log(res.data);
              if (res.data.token) {
                  $.ajax({
                      type: "post",
                      dataType: "json",
                      contentType: "application/json",
                      data: JSON.stringify({ "url": res.data.frontUrl }),
                      headers: {
                          token: res.data.token
                      },
                      url: baseUrl + '/ue/authority', //路径
                      success: function(ress) {
                          ress.data.bEncrypt = isbEncrypt || ress.data.bUseCryptoMode
                          initMQTT(ress.data);
                      }
                  })
                  if (res.data.frontUrl) {
                      if (res.data.token) {
                          let token = res.data.token ? res.data.token.slice(0, 12) + '3dxr' + res.data.token.slice(12, res.data.token.length) : '';
                          $("#yxrIframe").attr("src", res.data.frontUrl + '?id=' + token);
                      } else {
                          $("#yxrIframe").attr("src", res.data.frontUrl);
                      }
                  }
                  return
              } else {
                  setTimeout(() => {
                      getSecQXFun()
                  }, 3000)
              }
          }
      } else {
          const mySdkMsg = new sdkMsg();
          mySdkMsg.error("初始化接口调用失败,错误信息:" + res.message + ",错误号:errorCode=> 300001");
          showPopByInfo(res.message)
          reconnectionTime = setTimeout(() => {
              initApiFun(initApiFunPar.proId, initApiFunPar.sid, initApiFunPar.callBack, initApiFunPar.type, initApiFunPar.bEncrypt, initApiFunPar.inType)
          }, 3000)
      }
  }
  function getSecQXFun() {
      let key = localStorage.getItem('edouardSDKTokenApi') || ''
      if (getQueryString('TempSecret')) {
          let header = {
              TempSecret: getQueryString("TempSecret").split('#/')[0],
          }
          $.ajax({
              url: baseUrl + "/ue/verify" + "Secret",
              contentType: "application/json",
              data: JSON.stringify({ "userName": "", "pwd": "", "fromType": 'fx' }),
              headers: header,
              type: "POST",
              dataType: "json",
              success: function(data) {
                  if (data.status == 1) {
                      removePop()
                      data.data.bEncrypt = data.data.bUseCryptoMode || isbEncrypt
                      initMQTT(data.data);
                      if ($("#yxrIframe").length != 1) {
                          mySdkMsg.info("当前页面未发现ID为yxrIframe的iframe元素！无法渲染云地址！,错误号:errorCode=> 900001");
                      }
                      if (data.data.frontUrl) {
                          let token = getQueryString("TempSecret").slice(0, 12) + '3dxr' + getQueryString("TempSecret").slice(12, getQueryString("TempSecret").length)
                          $("#yxrIframe").attr("src", data.data.frontUrl + '?TempSecret=' + token);
                      }
                  } else {
                      showPopByInfo(data.message)
                      reconnectionTime = setTimeout(()=>{
                        initApiFun(initApiFunPar.proId, initApiFunPar.sid, initApiFunPar.callBack, initApiFunPar.type, initApiFunPar.bEncrypt, initApiFunPar.inType)
                      },3000)
                  }
              }
          })
          return
      }
      if (!key) {
          if ($('.centerDiv').length > 0) {
              $('.centerDiv').append(sdkLogin)
          } else {
              appendPop(sdkLogin)
          }
          $('#fruits').click(function() {
              if ($(this).is(':checked')) {
                  $('.sleectTimeVal').find('.info').hide()
              }
          })
          $('.sleectTimeVal').click(function() {
              if ($('#fruits').is(':checked')) {
                  $(this).find('.info').toggle()
              }
          })
          $('.sleectTimeVal .info p').mouseout(function() {
              $(this).css('background', '')
          })
          $('.sleectTimeVal .info p').mouseover(function() {
              $(this).css('background', '#000')
          })
          $('.sleectTimeVal .info p').click(function() {
              $('.showTxtSelect').text($(this).text())
              $('.showTxtSelect').attr('attr-value', $(this).attr('attr-value'))
          })
          $('.loginBySDK').on('click', function() {
              $.ajax({
                  url: baseUrl + "/ue/yxrLogin",
                  contentType: "application/json",
                  data: JSON.stringify({ "userName": $('.userNameLogin').val(), "pwd": Encrypt($('.userPwdLogin').val()) }),
                  type: "POST",
                  success: function(data) {
                      if (data.status == 1) {
                          $('.addPopLoginSDK').remove()
                          localStorage.setItem('edouardSDKTokenApi', data.data.token)
                          nextInit(initApiFunPar.proId, initApiFunPar.sid, initApiFunPar.callBack, initApiFunPar.type, initApiFunPar.bEncrypt, data.data.token)
                      } else {
                          if (data.message.indexOf('密码') > -1) {
                              $('.playerPage .entrypassword').css('color', 'red').html(data.message)
                          } else {
                              $('.playerPage .entrypassword').css('color', '#A1A1A1').html('请输入您的密码')
                          }
                          if (data.message.indexOf('用户') > -1) {
                              $('.playerPage .entryusername').css('color', 'red').html(data.message)
                          } else {
                              $('.playerPage .entryusername').css('color', '#A1A1A1').html('请输入您的账号')
                          }
                      }
                  },
                  dataType: "json"
              })
          })
          return
      } else {
          nextInit(initApiFunPar.proId, initApiFunPar.sid, initApiFunPar.callBack, initApiFunPar.type, initApiFunPar.bEncrypt, key)
      }
  }
